package com.ht.daoimpl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ht.model.Person;


public class HibernateDao extends HibernateDaoSupport{


	public int insert(Object o) {
		int result = 0;
		try {
			this.getHibernateTemplate().save(o);
			result = 1;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	public int delete(Object o) {
		int result = 0;
		try {
			this.getHibernateTemplate().delete(o);
			result = 1;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	public int update(Object o) {
		Session session = null;
		Transaction tran = null;
		int result = 0;
		try {
			this.getHibernateTemplate().update(o);
			result = 1;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}
	

	public Object get(Class c,Serializable id ){
		Object o= this.getHibernateTemplate().get(c, id);
		return o ;
		
	}

	public Object getUniqueObject(String hql, Object[] args) {
		Object o = null;
		try {
			List list = this.getHibernateTemplate().find(hql, args);
			if (list != null && list.size() > 0) {
				o = list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return o;

	}

	public List exeQuery(String hql, Object[] args) {
		List list = this.getHibernateTemplate().find(hql, args);
		return list;
	}

	public List exeQueryByPage(final String hql,final Object[] args, final int curPage, final int pageSize) {
		
		List<Person> list = new ArrayList();
		list = this.getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if(args!=null){
					for(int i=0;i<args.length;i++){
						query.setParameter(i,args[i]);
					}
				}
				query.setFirstResult((curPage - 1) * pageSize);
				query.setMaxResults(pageSize);
				List ls = query.list();
				return ls;
			}

		}
		);
		
		return list;

	}

}
